import 'package:flutter/material.dart';
import 'package:flutter_webrtc/flutter_webrtc.dart';
import 'package:socket_io_client/socket_io_client.dart' as IO;

class LiveWidget extends StatefulWidget {
  const LiveWidget({super.key});

  @override
  State<LiveWidget> createState() => _LiveWidgetState();
}

class _LiveWidgetState extends State<LiveWidget> {
  late RTCPeerConnection _peerConnection;
  late IO.Socket _socket;
  final _localRenderer = RTCVideoRenderer();
  final _remoteRenderer = RTCVideoRenderer();

  MediaStream? _localStream;

  @override
  void initState() {
    super.initState();
    // _initRenderers();
    // _connectSocket();
    // _createPeerConnection();
  }

  @override
  void dispose() {
    _localRenderer.dispose();
    _remoteRenderer.dispose();
    _socket.dispose();
    super.dispose();
  }

  void _initRenderers() async {
    await _localRenderer.initialize();
    await _remoteRenderer.initialize();
  }

  void _connectSocket() {
    _socket = IO.io('http://localhost:3000', <String, dynamic>{
      'transports': ['websocket'],
    });

    _socket.on('offer', (data) async {
      await _peerConnection.setRemoteDescription(RTCSessionDescription(data['sdp'], data['type']));
      var answer = await _peerConnection.createAnswer();
      await _peerConnection.setLocalDescription(answer);
      _socket.emit('answer', {'sdp': answer.sdp, 'type': answer.type});
    });

    _socket.on('answer', (data) async {
      await _peerConnection.setRemoteDescription(RTCSessionDescription(data['sdp'], data['type']));
    });

    _socket.on('ice-candidate', (data) async {
      var candidate = RTCIceCandidate(data['candidate'], data['sdpMid'], data['sdpMLineIndex']);
      await _peerConnection.addCandidate(candidate);
    });
  }

  void _createPeerConnection() async {
    var configuration = {
      'iceServers': [
        {'urls': 'stun:stun.l.google.com:19302'},
      ]
    };

    _peerConnection = await createPeerConnection(configuration);

    _peerConnection.onIceCandidate = (candidate) {
      if (candidate != null) {
        _socket.emit('ice-candidate', {
          'candidate': candidate.candidate,
          'sdpMid': candidate.sdpMid,
          'sdpMLineIndex': candidate.sdpMLineIndex,
        });
      }
    };

    _peerConnection.onAddStream = (stream) {
      _remoteRenderer.srcObject = stream;
    };

    var stream = await navigator.mediaDevices.getUserMedia({'video': true, 'audio': true});
    _localRenderer.srcObject = stream;
    _peerConnection.addStream(stream);

    _localStream = await navigator.mediaDevices.getUserMedia({'video': true, 'audio': true});
    _localRenderer.srcObject = _localStream;
    _peerConnection.addStream(_localStream!);
  }

  void _startLiveStream() async {
    _initRenderers();
    _connectSocket();
    _createPeerConnection();
  }

  void _stopLiveStream() async {
    _localStream?.getTracks().forEach((tract) => tract.stop());

    await _peerConnection.close();

    _socket.disconnect();

    _localRenderer.srcObject = null;
    _remoteRenderer.srcObject = null;

    setState(() {
      
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          alignment: Alignment.center,
          width: double.infinity,
          child: const Text('直播'),
        ),
        Expanded(child: RTCVideoView(_localRenderer)),
        Expanded(child: RTCVideoView(_remoteRenderer)),
        ElevatedButton(
          onPressed: _startLiveStream,
          child: const Text('开始直播'),
        ),
        ElevatedButton(
          onPressed: _stopLiveStream,
          child: const Text('停止直播'),
        )
      ],
    );
  }
}